<template>
  <div>
    <el-dialog
      :title="label"
      :visible.sync="visible"
      v-if="visible"
      width="800px"
      :before-close="handleClose"
      center
      append-to-body
      ref="dialog"
    >
      <div class="member-index">
        <tx-block>
          <tx-button-add
            :name="generateTitle()"
            @click="add"
            v-if="action == 'modify'"
          />
          <el-form ref="form" :model="form" label-width="0px">
            <tx-list-table
              :table="table"
              ref="listTable"
              row-key="name"
              v-loading="table.loading"
            >
              <tx-table-column-text label="排序" width="60">
                <template slot-scope="scope"
                  ><span class="number-index">{{
                    scope.scope.scope.$index + 1
                  }}</span></template
                >
              </tx-table-column-text>
              <tx-table-column-text label="内设机构名称">
                <template slot-scope="scope">
                  <tx-table-input
                    :entity="scope.row"
                    name="name"
                    :action="scope.row.$action"
                    :rules="$rule.requireds('请输入内设机构名称')"
                    :prop="buildRowProp(scope, 'name')"
                    placeholder="请输入内设机构名称"
                  />
                </template>
              </tx-table-column-text>
              <tx-table-column-text label="可添加最大人数">
                <template slot-scope="scope">
                  <tx-table-input
                    :entity="scope.row"
                    name="maxUserNumber"
                    :action="scope.row.$action"
                    :rules="formRules.maxUserNumber"
                    :prop="buildRowProp(scope, 'maxUserNumber')"
                    placeholder="请输入可添加最大人数"
                  />
                </template>
              </tx-table-column-text>
              <tx-table-column-text label="已添加用户数">
                <template slot-scope="scope">
                  {{ scope.row.userNumber || 0}}
                  <!-- <tx-table-input
                    :entity="scope.row"
                    name="userNumber"
                    :action="scope.row.$action"
                    :rules="$rule.requireds('请输入已添加用户数')"
                    :prop="buildRowProp(scope, 'userNumber')"
                    placeholder="请输入已添加用户数"
                  /> -->
                </template>
              </tx-table-column-text>

              <tx-table-column-action
                width="250"
                align="left"
                :key="$columnKey()"
              >
                <template slot-scope="scope">
                  <el-form
                    :ref="`form${scope.scope.scope.$index}`"
                    :model="form.record"
                    :rules="formRules"
                    style="display: none"
                  >
                    <!-- <tx-form-input :entity="form.record" name="orgName" /> -->
                    <tx-form-input :entity="form.record" name="name" />
                    <tx-form-input :entity="form.record" name="maxUserNumber" />
                    <!-- <tx-form-input :entity="form.record" name="userNumber" /> -->
                  </el-form>
                  <!-- <tx-link text="编辑" name="dept" :query="{itemId: scope.row.itemId}"  />
                          <tx-link text="删除" name="dept" :query="{itemId: scope.row.itemId}"  />  -->
                  <el-button
                    type="primary"
                    size="mini"
                    v-if="scope.row.$action != 'modify' && action == 'modify'"
                    class="table-edit-btn"
                    @click="handleEdit(scope, scope.scope.scope.$index)"
                    >编辑
                  </el-button>
                  <el-button
                    type="primary"
                    size="mini"
                    v-if="scope.row.$action == 'modify'"
                    @click="handleSave(scope)"
                    class="table-save-btn"
                    v-preventReClick="3000"
                    >保存
                  </el-button>
                  <el-button
                    size="mini"
                    type="warning"
                    v-if="scope.row.$action == 'modify'"
                    @click="handleCancel(scope, scope.scope.scope.$index)"
                    class="table-cancel-btn"
                    >取消
                  </el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    v-if="scope.row.$action != 'modify' && action == 'modify'"
                    @click="handleDelete(scope)"
                    class="table-del-btn"
                    >删除
                  </el-button>
                </template>
              </tx-table-column-action>
            </tx-list-table>
          </el-form>
        </tx-block>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose()" :disabled="loading">取消</el-button>
        <el-button type="primary" @click="handleConfirm()" :disabled="loading"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import TxTableInput from "@/components/tx/tx-form/TxTableInput.vue";
// 内设机构
export default {
  components: { TxTableInput },
  name: "ysjg-list",
  props: {
    ysjgData: {
      type: [Array],
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      action: "",
      visible: false,
      ysjgData1: null,
      loading: false,
      table: {
        loading: false,
        page: this.$yzvue.initPage(),
      },
      form: {
        record: {
          name: "",
          maxUserNumber: "",
          // userNumber: "",
        },
        records: [],
      },
      formRules: {
        name: this.$rule.name("内设机构名称", null, 32),
        // maxUserNumber: this.$rule.name("可添加最大人数", null, 32),
        // userNumber: this.$rule.name("已添加用户数", null, 32),
      },
    };
  },
  mounted() {
    this.loadTable();
  },
  computed: {
    disabledEdit() {
      return function (phone) {
        return (
          this.$userInfo.phone == phone &&
          ["1000000007", "1000000015", "1000000016"].includes(
            this.getParameter("menuId")
          )
        );
      };
    },
  },
  methods: {
    open(action) {
      this.visible = true;
      this.action = action;
    },
    handleQuery() {
      this.loadTable();
    },
    async loadTable() {
      this.ysjgData1 = this.$lodash.cloneDeep(this.ysjgData);
      this.ysjgData1 = this.ysjgData1.map((item) => {
        return {
          ...item,
          maxUserNumber: String(item.maxUserNumber),
          userNumber: String(item.userNumber),
        };
      });
      this.$yzvue.assembleBody(this.table.page, { records: this.ysjgData1 });
      this.form.records = this.ysjgData1;

      // this.$yzvue.assembleBody(this.table.page, {
      //   records: this.$lodash.cloneDeep(this.ysjgData),
      // });
      // this.form.records = this.$lodash.cloneDeep(this.ysjgData);
    },

    buildRowProp($scope, field) {
      let {
        scope: { scope },
      } = $scope;
      return `records.${scope.$index}.${field}`;
    },
    // 新增
    add() {
      Object.keys(this.form.record).forEach((v) => {
        this.form.record[v] = "";
      });
      let newRow = this.$lodash.cloneDeep({
        ...this.form.record,
        $action: "modify",
      });
      this.table.page.records.push(newRow);
    },
    // 编辑
    handleEdit($scope, index) {
      let obj = {
        ...$scope.row,
        $action: "modify",
        $origin: {
          id: $scope.row.id,
          name: $scope.row.name,
          maxUserNumber: $scope.row.maxUserNumber,
          uerNumber: $scope.row.uerNumber,
        },
      };
      this.$set(this.table.page.records, index, obj);
      // let { name } = $scope.row;
      // this.table.page.records.forEach((item) => {
      //   if (item.name == name) {
      //     item.$action = "modify";
      //     item.$origin = {
      //       id: $scope.row.id,
      //       name: $scope.row.name,
      //       maxUserNumber: $scope.row.maxUserNumber,
      //       uerNumber: $scope.row.uerNumber,
      //     };
      //   }
      // });

      // $scope.row.$action = "modify";

      // $scope.row.$origin = {
      //   id: $scope.row.id,
      //   name: $scope.row.name,
      //   maxUserNumber: $scope.row.maxUserNumber,
      //   uerNumber: $scope.row.uerNumber,
      // };

      // let newRow = this.$lodash.cloneDeep({
      //   ...this.form.record,
      //   $action: "modify",
      // });
      // this.table.page.records.push(newRow);
    },
    // 保存
    handleSave($scope) {
      Object.assign(this.form.record, $scope?.row || {});
      let { name, maxUserNumber, userNumber } = this.form.record;
      this.$handleFormValidate(`form${$scope.scope.scope.$index}`, async () => {
        console.log(this.table.page.records);

        if (this.table.page.records.filter((i) => i.name == name)?.length > 1) {
          this.$message.error("内设机构名字不能重复存在");
          return false;
        }

        if(!/^\+?[1-9][0-9]*$/.test(Number(maxUserNumber))) {
          this.$message.error("可添加最大人数必须是大于0的整数");
          return false
        }
        if (Number(maxUserNumber) < Number($scope?.row.userNumber)) {
          this.$message.error("可添加最大人数必须大于已添加用户数");
          return false
        }
          this.SubmitEvent($scope);
       
      });
    },
    // 保存
    SubmitEvent($scope) {
      $scope.row.$action = "view";
      // let { id, name} = this.form.record;
      // this.ysjgData.filter(i=>i.name==name)
      // this.table.loading = false;
    },
    // 取消
    handleCancel($scope, index) {
      Object.assign($scope.row, $scope.row.$origin);
      $scope.row.$action = "view";
      this.$set(this.table.page.records, index, $scope.row);
      this.$refs["form"].clearValidate();
    },
    //删除
    handleDelete($scope) {
      let { id } = $scope.row;
      let {
        scope: { scope },
      } = $scope;
      if (id) {
        this.$confirm("请确认是否直接将此预设机构删除？").then((res) => {
          this.$api.OrgController.delete({ body: { orgId: id } }, (res) => {
            if (res.code == 0) {
              this.table.page.records.splice(scope.$index, 1);
            }
          });
        });
      } else {
        this.table.page.records.splice(scope.$index, 1);
      }

      // 请求后台接口删除数据库数据
    },
    updateSort() {
      if (this.allowSort == false) {
        this.$initDragTable(
          this.$refs["listTable"],
          this.table.page,
          "records"
        );
        this.beforeSortData = JSON.parse(
          JSON.stringify(this.table.page.records)
        );
      } else {
        let params = this.table.page.records
          ?.filter((i) => i.id)
          ?.map((i, k) => {
            return {
              id: i.orgId,
              udOrder: k + 1,
            };
          });
        this.$api.OrgController.sort({ body: params }, (res) => {
          if (res.code == 0) {
            this.loadTable();
            this.$stopDragTable();
          }
        });
      }
      this.allowSort = !this.allowSort;
    },
    cancelSort() {
      this.allowSort = !this.allowSort;
      // this.this.table.page.records = this.beforeSortData
      // this.$initDragTable(this.$refs["listTable1"],
      //       this.table.page,
      //       "records1")
      this.$stopDragTable();
      this.loadTable();
    },
    // 重置按钮文本
    generateTitle() {
      // let userOrgName=this.$userInfo.orgName;
      // let orgNames=["应急厅","应急局","应急管理局","应急管理厅"]
      // if(orgNames.includes(userOrgName) ){
      //   return  "内设机构"
      // }
      return "安全生产、防灾减灾内设机构";
    },
    handleClose() {
      this.visible = false;
    },
    handleConfirm() {
      if (
        this.table.page.records.filter((i) => i.$action == "modify").length > 0
      ) {
        this.$message.error("内设机构列表有未保存的数据，请先保存");
        return false;
      }
      let filterData = this.table.page.records.filter(
        (i) =>
          i.id ||
          (i.name && i.maxUserNumber  && i.$action == "view")
      );
      this.$emit("update", filterData);
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scope>
.member-index {
  .el-form-item {
    margin-bottom: 0px !important;
  }
  .tx-list-query {
    margin: 0px;

    // border: 2px solid $c-bd-menu;
  }

  .tx-block {
    width: auto;
    margin: 15px 0px;
    background-color: $c-bg-query;
    border: 1px solid $c-bd-content;
  }

  .el-table td.el-table__cell {
    padding: 8px 0px 0px 0px;
    div {
      margin-bottom: 0px;
    }
    .cell > span {
      display: block;
      padding-bottom: 13px;
      line-height: 30px;
    }
    .tx-table-column-action {
      display: block;
      padding-bottom: 10px;
    }

    .el-input__inner {
      height: 30px;
      line-height: 30px;
      padding: 0px 5px;
    }
    .el-form-item {
      margin-bottom: 13px !important;
    }
    .el-form-item__content {
      line-height: 30px;
    }
    .el-form-item__error {
      padding-top: 0px;
    }
  }
}
.btnbox-right {
  display: flex;
  align-items: center;
  float: right;
  .tooltip {
    margin-left: 10px;
    width: 16px;
    height: 16px;
    cursor: pointer;
    background: url("~@/assets/TeamAdministrator/icon_explain.png") no-repeat;
  }
}
</style>
